package com.hiking.jwt.handler;

import com.corundumstudio.socketio.*;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.hiking.jwt.domain.UserBean;
import com.hiking.jwt.model.*;
import com.hiking.jwt.repository.UserRepository;
import com.hiking.jwt.service.UserService;
import io.socket.client.Ack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * 消息事件处理器
 * https://blog.csdn.net/arsiya_jerry/article/details/78731347   api
 *
 * @author XiongNeng
 * @version 1.0
 * @since 2018/1/19
 */
//@Component
public class MessageEventHandler {

    private final SocketIOServer server;

    private static final Logger logger = LoggerFactory.getLogger(MessageEventHandler.class);

//    @Autowired
    UserRepository userRepository;

//    @Autowired
    public MessageEventHandler(SocketIOServer server) {
        this.server = server;
    }

//    //添加connect事件，当客户端发起连接时调用
//    @OnConnect
//    public void onConnect(SocketIOClient client) {
//        String token = client.getHandshakeData().getSingleUrlParam("token");
//
//        UserBean userBean = userRepository.findByToken(token);
//
//        if (client != null) {
//            String username = client.getHandshakeData().getSingleUrlParam("username");
//            String password = client.getHandshakeData().getSingleUrlParam("password");
//            String sessionId = client.getSessionId().toString();
//            logger.info("连接成功, username=" + username + ", password=" + password + ", sessionId=" + sessionId);
//
//            //            client.joinRoom(client.getHandshakeData().getSingleUrlParam("appid"));
////            client.joinRoom(client.getHandshakeData().getSingleUrlParam("username"));
////            client.joinRoom("room1");
//            socket_Map.put(userBean.getUsername(), client);
//        } else {
//            logger.error("客户端为空");
//        }
//    }

    //添加@OnDisconnect事件，客户端断开连接时调用，刷新客户端信息
//    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        logger.info("客户端断开连接, sessionId=" + client.getSessionId().toString());
        client.disconnect();
    }


    HashMap<String, SocketIOClient> socket_Map = new HashMap<>();
    final boolean[] result = {false};

//    @OnEvent(value = "chat")
    public void onChat(SocketIOClient client, AckRequest callback, MessageModel message) {
        if (callback.isAckRequested()) {
            callback.sendAckData(message);
        }
        String to_user = message.getTo_user();
        if (socket_Map.containsKey(to_user)) {
            SocketIOClient voIo = socket_Map.get(to_user);

            /**
             * AckCallback用于超时回调
             * 客户端接收时参数在最后一个
             * https://blog.csdn.net/danengbinggan33/article/details/78273478?locationNum=10&fps=1
             */
            voIo.sendEvent("chat", new AckCallback(String.class, 1000) {
                @Override
                public void onSuccess(Object o) {
                    logger.info(o.toString());
                }

            }, message);
//            voIo.sendEvent("chat", message);
        }

    }

    // 消息接收入口
//    @OnEvent(value = "chat1111")
    public void onEvent(SocketIOClient client, AckRequest ackRequest, MessageModel chat) {
        logger.info("接收到客户端消息");
        if (ackRequest.isAckRequested()) {
            // send ack response with data to client
            ackRequest.sendAckData("服务器回答chatevent, userName=" + chat.getFrom_user() + ",message=" + chat.getBodies().getMsg());
        }
//        String room = client.getHandshakeData().getSingleUrlParam("username");
        server.getRoomOperations("room1").sendEvent("chat", "hhhhh");
    }

    // 登录接口
//    @OnEvent(value = "login")
    public void onLogin(SocketIOClient client, AckRequest ackRequest, LoginRequest message) {
        logger.info("接收到客户端登录消息");
        if (ackRequest.isAckRequested()) {
            // send ack response with data to client
            ackRequest.sendAckData("服务器回答login", message.getCode(), message.getBody());
        }
        // 向客户端发送消息
        List<String> list = new ArrayList<>();
        list.add("登录成功，sessionId=" + client.getSessionId());
        // 第一个参数必须与eventName一致，第二个参数data必须与eventClass一致
        String room = client.getHandshakeData().getSingleUrlParam("appid");
        server.getRoomOperations(room).sendEvent("login", list.toString());
//        client.sendEvent("login","hhh");
    }

//    @OnConnect
    public void onConnect(SocketIOClient client) {
    }

//    @OnEvent(value = "new message")
    public void onNewMessage(SocketIOClient client, String message, String username) {
        DataBean dataBean = new DataBean();
        dataBean.setUsername(username);
        dataBean.setMessage(message);
        server.getRoomOperations("room").sendEvent("new message", dataBean);

    }


    /**
     * 注意：客户端事件发送参数一定要和服务器的接收一样
     * 比如客户端：socket.emit("hello",JavaBean)
     * 服务器就要写成:函数名(SocketIOClient client,JavaBean)
     * 否则，接收不到！
     */
//    @OnEvent(value = "add user")
    public void onAddUser(SocketIOClient client, String username) {
        System.out.println("onAddUser");
        DataBean dataBean = new DataBean();
        dataBean.setNumUsers(3);
        dataBean.setUsername(username);
        client.sendEvent("login", dataBean);
        client.sendEvent("user joined", dataBean);
        client.joinRoom("room");
    }

//    @OnEvent(value = "user left")
    public void onUserLeft() {

    }

//    @OnEvent(value = "typing")
    public void onTyping() {

    }

//    @OnEvent(value = "stop typing")
    public void onStopTyping() {

    }


}
